package main

import (
	"log"
	"net/http"

	"library/controllers"
	"library/models"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func main() {
	// 连接 MySQL 数据库（请根据实际修改用户名、密码、地址、库名）
	dsn := "root:123456@tcp(127.0.0.1:3306)/library?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		log.Fatalf("数据库连接失败: %v", err)
	}
	// 将 db 对象传递给 controllers 包
	controllers.DB = db

	// 自动迁移表结构（创建books、categories、users、borrows、logs五张表）
	db.AutoMigrate(&models.Book{}, &models.Category{}, &models.User{}, &models.Borrow{}, &models.Log{})

	// 初始化 Gin 引擎
	router := gin.Default()
	// 设置静态资源目录和模板目录
	router.Static("/static", "./static")
	router.LoadHTMLGlob("templates/*")

	// 首页路由
	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})

	// 图书管理路由
	router.GET("/books", controllers.GetBooks)
	router.GET("/books/add", controllers.ShowAddBookPage)
	router.POST("/books/add", controllers.AddBook)
	router.GET("/books/edit/:id", controllers.ShowEditBookPage)
	router.POST("/books/edit/:id", controllers.EditBook)
	router.GET("/books/delete/:id", controllers.DeleteBook)
	router.GET("/books/:id", controllers.BookDetail)

	// 分类管理路由
	router.GET("/categories", controllers.GetCategories)
	router.GET("/categories/add", controllers.ShowAddCategoryPage)
	router.POST("/categories/add", controllers.AddCategory)
	router.GET("/categories/edit/:id", controllers.ShowEditCategoryPage)
	router.POST("/categories/edit/:id", controllers.EditCategory)
	router.GET("/categories/delete/:id", controllers.DeleteCategory)

	// 用户管理路由
	router.GET("/users", controllers.GetUsers)
	router.GET("/users/add", controllers.ShowAddUserPage)
	router.POST("/users/add", controllers.AddUser)
	router.GET("/users/edit/:id", controllers.ShowEditUserPage)
	router.POST("/users/edit/:id", controllers.EditUser)
	router.GET("/users/delete/:id", controllers.DeleteUser)

	// 借阅管理路由
	router.GET("/borrows", controllers.GetBorrows)
	router.GET("/borrows/add", controllers.ShowAddBorrowPage)
	router.POST("/borrows/add", controllers.AddBorrow)
	router.GET("/borrows/return/:id", controllers.ReturnBorrow)
	router.GET("/borrows/delete/:id", controllers.DeleteBorrow)

	// 日志查看路由
	router.GET("/logs", controllers.GetLogs)

	// 启动服务器
	router.Run(":8080")
}
